package org.cloud.gateway.filter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.cloud.api.auth.client.client.SlothAuthenticationClient;
import org.cloud.common.model.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

/**
 * 前台接口鉴权拦截器
 * @author wangyuan
 * @since 2019年6月4日 上午11:40:25
 *
 */
@Component
public class ApiAccessFilter extends ZuulFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(ApiAccessFilter.class);
	
	private static final List<String> INCLUDE_URI_PATTERNS = new ArrayList<>();
	static {
		INCLUDE_URI_PATTERNS.add("^(/api/).*");
	}
	
	@Resource
	private SlothAuthenticationClient slothAuthenticationClient;

	@Override
	public boolean shouldFilter() {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		
		String servletPath = request.getServletPath();
		for(String item : INCLUDE_URI_PATTERNS) {
			if(Pattern.matches(item, servletPath)) {
				logger.info("过滤器{}将应用在请求{}之上", getClass().getSimpleName(), servletPath);
				return true;
			}
		}
		
		return false;
	}

	@Override
	public Object run() throws ZuulException {
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		String servletPath = request.getServletPath();
		//获取去掉统一请求前缀的uri
		String requestUri = servletPath.substring(servletPath.indexOf("/"));
		requestUri = requestUri.substring(servletPath.indexOf("/"));
		
		logger.info("请求的ContentType：{}", request.getContentType());
		logger.info("请求的URI：{}", requestUri);
		
		//TODO 请求验证逻辑
		R r = slothAuthenticationClient.authenticateService(requestUri);
		logger.info("验证结果：{}", r);
		
		return true;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

}
